package com.vhall.component.service.interactive.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vhall.component.dao.account.AccountMapper;
import com.vhall.component.dao.interactive.DocumentsRoomMapper;
import com.vhall.component.entity.account.AccountEntity;
import com.vhall.component.entity.interactive.vo.*;
import com.vhall.component.entity.room.RoomDocumentsEntity;
import com.vhall.component.entity.room.dto.RoomsEntityDTO;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.support.TokenThreadLocal;
import com.vhall.component.plugin.common.utils.UploadUtil;
import com.vhall.component.plugin.core.service.PaasService;
import com.vhall.component.service.interactive.DocumentsRoomService;
import com.vhall.component.service.room.RoomInnerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文档组件实现类
 *
 * @author shenqing
 */
@Slf4j
@Service
public class DocumentsRoomServiceImpl extends ServiceImpl<DocumentsRoomMapper, RoomDocumentsEntity> implements DocumentsRoomService {

    @Autowired
    private DocumentsRoomMapper documentsRoomMapper;

    @Autowired
    private PaasService paasService;

    @Autowired
    private RoomInnerService roomInnerService;

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public DocumentUploadRsp upload(DocumentUploadReqVO vo) {

        Integer accountId;
        accountId = vo.getAccountId();
        if (StrUtil.isNotEmpty(vo.getRoomId())){
            RoomsEntityDTO roomsEntity = roomInnerService.getRoomInfo(vo.getRoomId());
            if (roomsEntity != null) {
                accountId = roomsEntity.getAccountId();
            }
        }

        File dest = UploadUtil.upload(vo.getDocument(), "", "");

        //PaaS端创建文档信息
        JSONObject result = paasService.documentCreate(dest);
        if (null == result) {
            throw new BusinessException(BizErrorCode.BIZ_UPLOAD_FAILED);
        }
        String documentId = result.getString("document_id");
        Integer convertedTotal = result.getInteger("converted_total");
        Integer convertedTime = result.getInteger("converted_time");
        //PaaS端获取文档信息
        JSONObject fileInfo = paasService.documentInfo(documentId);

        String fileName = vo.getDocument().getOriginalFilename();
        String hash = fileInfo.getString("hash");
        String ext = fileInfo.getString("ext");

        //入db
        RoomDocumentsEntity doc = new RoomDocumentsEntity();
        doc.setAppId(paasService.getAppId());
        doc.setDocumentId(documentId);
        doc.setAccountId(accountId.toString());
        doc.setFileName(fileName);
        doc.setHash(hash);
        doc.setExt(ext);
        doc.setCreatedAt(LocalDateTime.now());
        doc.setUpdatedAt(LocalDateTime.now());
        if (StringUtils.isNotBlank(vo.getRoomId())) {
            doc.setRoomId(vo.getRoomId());
        } else {
            doc.setRoomId("");
        }
        documentsRoomMapper.insert(doc);

        DocumentUploadRsp rsp = new DocumentUploadRsp();
        rsp.setConvertedTime(convertedTime);
        rsp.setConvertedTotal(convertedTotal);
        BeanUtils.copyProperties(doc, rsp);


        return rsp;

    }

    @Override
    public DocumentListRspVO list(DocumentListReqVO reqVO) {
        LambdaQueryWrapper<RoomDocumentsEntity> where = Wrappers.lambdaQuery();
//
//        if (reqVO.getAccountId() == null) {
//            RoomsEntityDTO roomsEntity = findByRoomId(reqVO.getRoomId());
//            if (roomsEntity == null) {
//                throw new BusinessException(BizErrorCode.EMPTY_ROOM);
//            }
//            accountId = roomsEntity.getAccountId();
//        } else {
//            accountId = Integer.valueOf(reqVO.getAccountId());
//        }
        reqVO.setAccountId(null);
        Token token = TokenThreadLocal.getToken();
        if (token.getRoleType() == null){
            RoomsEntityDTO roomInfo = roomInnerService.getRoomInfo(reqVO.getRoomId());
            AccountEntity accountEntity = accountMapper.selectById(roomInfo.getAccountId());
            LambdaQueryWrapper<AccountEntity> accountEntityLambdaQueryWrapper = Wrappers.lambdaQuery();
            accountEntityLambdaQueryWrapper.eq(AccountEntity::getOrgCode, accountEntity.getOrgCode());
            List<AccountEntity> accountEntities = accountMapper.selectList(accountEntityLambdaQueryWrapper);
            List<Integer> accountIdsOfOrg = accountEntities.stream().map(AccountEntity::getAccountId).collect(Collectors.toList());
            where.in( RoomDocumentsEntity::getAccountId, accountIdsOfOrg);
        }else {
            if (token.getRoleType() == 2){
                AccountEntity accountEntity = accountMapper.selectById(token.getAccountId());
                LambdaQueryWrapper<AccountEntity> accountEntityLambdaQueryWrapper = Wrappers.lambdaQuery();
                accountEntityLambdaQueryWrapper.eq(AccountEntity::getOrgCode, accountEntity.getOrgCode());
                List<AccountEntity> accountEntities = accountMapper.selectList(accountEntityLambdaQueryWrapper);
                List<Integer> accountIdsOfOrg = accountEntities.stream().map(AccountEntity::getAccountId).collect(Collectors.toList());
                where.in( RoomDocumentsEntity::getAccountId, accountIdsOfOrg);
            }else if (token.getRoleType() == 1){
                reqVO.setAccountId(null);
            }
        }

        //获取列表，查询逻辑
        if (StringUtils.isNotBlank(reqVO.getFileName())) {
            where.like(RoomDocumentsEntity::getFileName, reqVO.getFileName().trim());
        }
        where.orderByDesc(RoomDocumentsEntity::getCreatedAt);
        Page<RoomDocumentsEntity> page = new Page<>(reqVO.getCurrPage(), reqVO.getPageSize());
        page = documentsRoomMapper.selectPage(page, where);

        DocumentListRspVO vo = new DocumentListRspVO();
        vo.setCurrPage(reqVO.getCurrPage());
        vo.setPageSize(reqVO.getPageSize());
        vo.setTotal((int) page.getTotal());
        vo.setDetail(page.getRecords());
        return vo;
    }

    @Override
    public Boolean delete(DocumentDeleteReqVO reqVO) {

        //PaaS端删除文档
        paasService.documentDel(reqVO.getDocumentId());
        //db删除（物理删除）文档
        LambdaQueryWrapper<RoomDocumentsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RoomDocumentsEntity::getAppId, paasService.getAppId())
                .eq(RoomDocumentsEntity::getDocumentId, reqVO.getDocumentId());
        documentsRoomMapper.delete(wrapper);
        return true;
    }

    @Override
    public Boolean update(DocumentUpdateReqVO param) {
        //判断文档是否存在
        LambdaQueryWrapper<RoomDocumentsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RoomDocumentsEntity::getDocumentId, param.getDocumentId());
        RoomDocumentsEntity entity = documentsRoomMapper.selectOne(wrapper);
        if (entity == null) {
            throw new BusinessException(BizErrorCode.EMPTY_DOCUMENT);
        }
        //PaaS端获取文档信息
        JSONObject file = paasService.documentInfo(param.getDocumentId());
        //获取PaaS响应参数
        Integer transStatus = file.getInteger("trans_status");
        Integer page = file.getInteger("page");
        String statusJpeg = String.valueOf(file.getInteger("status_jpeg"));
        String statusSwf = file.getString("status_swf");
        String status = String.valueOf(file.getInteger("status"));
        //入db
        entity.setTransStatus(transStatus);
        entity.setPage(page);
        entity.setStatusJpeg(statusJpeg);
        entity.setStatusSwf(statusSwf);
        entity.setStatus(status);
        entity.setUpdatedAt(LocalDateTime.now());

        int effect = documentsRoomMapper.updateById(entity);

        return effect == 1;
    }

    /**
     * 根据文档id,房间id 查询文档信息
     *
     * @param documentId 文档id
     * @param roomId     房间id
     * @return
     */
    @Override
    public RoomDocumentsEntity getInfo(String documentId, String roomId) {
        LambdaQueryWrapper<RoomDocumentsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RoomDocumentsEntity::getAppId, paasService.getAppId())
                .eq(RoomDocumentsEntity::getDocumentId, documentId)
                .eq(StringUtils.isNotBlank(roomId), RoomDocumentsEntity::getRoomId, roomId);
        wrapper.last(" limit 1");
        return documentsRoomMapper.selectOne(wrapper);
    }

    public RoomsEntityDTO findByRoomId(String roomId) {
        RoomsEntityDTO room = roomInnerService.getRoomInfo(roomId);
        if (null == room) {
            throw new BusinessException(BizErrorCode.EMPTY_ROOM);
        }
        return room;
    }
}
